<template>
  <div class="headerContainer">
    <!-- 头部左侧区域 -->
    <div class="left">
      <ul>
        <!-- 遍历显示所有头条分类，点击时切换高亮状态 -->
        <li @click="HighlightHandler(index)" v-for="(item,index) in findAllTypeList" :key="item.tid">
          <a :class="{ active: item.isHighlight }" href="javascript:;">{{item.tname}}</a>
        </li>
      </ul>
    </div>
    <!-- 头部右侧区域 -->
    <div class="right">
      <div class="rightInput" style="margin-right: 50px;">
        <!-- 搜索框，用于搜索最新头条 -->
        <el-input v-model="keywords" placeholder="搜索最新头条" clearable>
          <template #append>
            <el-button :icon="Search" />
          </template>
        </el-input>
      </div>

      <!-- 用户登录以后的展示 -->
      <div class="btn-dropdown">
        <!-- 用户没有登录的时候的展示 -->

        <!-- 用户已登录时显示用户信息和操作菜单 -->
        <div v-if="nickName" style="display: flex; justify-content: center; align-items: center;">
          <el-dropdown>
            <el-button type="primary">
              您好:{{ nickName }}<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handlerNews">发布新闻</el-dropdown-item>
                <el-dropdown-item>个人中心</el-dropdown-item>
                <el-dropdown-item>浏览记录</el-dropdown-item>
                <el-dropdown-item @click="Logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <!-- 用户未登录时显示登录和注册按钮 -->
        <div v-else class="containerButton">
          <el-button size="small" style="background: #212529; color: #aea7a2" @click="toLogin">登录</el-button>
          <el-button size="small" style="background: #ffc107; color: #684802" @click="toRegister">注册</el-button>
        </div>

      </div>
    </div>
  </div>
</template>

<script setup>
/**
 * Header 组件
 * 
 * 页面头部组件，包含导航分类、搜索功能和用户登录状态显示
 */
import { getfindAllTypes, isUserOverdue } from '../api/index'
import { ref, onMounted, getCurrentInstance, watch, onUpdated } from "vue"
import { useRouter } from 'vue-router'
import { ArrowDown, Search } from '@element-plus/icons-vue'
import { removeToken } from '../utils/index.js'
import pinia from '../stores/index';
import { useUserInfoStore } from '../stores/userInfo'



// 获取全局事件总线实例
const { Bus } = getCurrentInstance().appContext.config.globalProperties


const router = useRouter()
// 用户信息状态管理
const userInfoStore = useUserInfoStore(pinia)
// 搜索关键词
const keywords = ref("") 
// 用户昵称
const nickName = ref("")

/**
 * 监听搜索关键词变化
 * 当搜索关键词发生变化时，通过事件总线向 HeadlineNews 组件传递新的关键词
 */
watch(keywords, (newVal) => {
  Bus.emit('keyword', newVal)
})

// 所有头条分类列表
const findAllTypeList = ref([])


const toLogin = () => {
  router.push({ name: "Login" });
}
const toRegister = () => {
  router.push({ name: "Register" });
}

/**
 * 获取所有头条分类数据
 * 
 * 从服务器获取所有头条分类，并在数据前添加"微头条"分类作为默认选中项
 */
const getList = async () => {
  let result = await getfindAllTypes()
  // 遍历数据添加高亮标识
  result.forEach((item) => {
    item.tid = item.tid
    item.tname = item.tname
    item.isHighlight = false
  })
  // 添加微头条数据
  result.unshift({
    isHighlight: true,
    tid: 0,
    tname: "首页"
  })
  findAllTypeList.value = result
}

/**
 * 在组件更新时同步用户昵称
 */
onUpdated(() => {
  nickName.value = userInfoStore.nickName
})


onMounted(() => {
  getList()
})

/**
 * 处理分类高亮切换
 * 
 * 使用排他思想，确保只有一个分类处于高亮状态，并通过事件总线传递选中的分类ID
 * @param {Number} index - 被点击分类在列表中的索引
 */
const HighlightHandler = (index) => {
  findAllTypeList.value.forEach((item) => {
    item.isHighlight = false
  })
  // 切换高亮的时候把tid传给HeadlineNews组件
  findAllTypeList.value[index].isHighlight = true
  Bus.emit('tid', findAllTypeList.value[index].tid)
}

/**
 * 用户退出登录处理
 * 
 * 清除用户token，重置用户信息状态，清空昵称并跳转到首页
 */
const Logout = () => {
  removeToken()
  userInfoStore.initUserInfo()
  nickName.value = ""
  router.go({ name: "HeadlineNews" });
}

/**
 * 发布新闻处理
 * 
 * 检查用户token是否过期，未过期则跳转到新闻发布页面
 */
const handlerNews = async () => {
  //发送请求判断用户是否token过期
  await isUserOverdue()
  router.push({ name: "addOrModifyNews" });
}
</script>

<style>
.el-dropdown {
  vertical-align: top;
  width: 120px;
}

.el-dropdown+.el-dropdown {
  margin-left: 15px;
}

.el-icon-arrow-down {
  font-size: 12px;
}
</style>

<style lang="less" scoped>
.headerContainer {
  width: 100%;
  height: 60px;
  background: linear-gradient(135deg, #212529, #495057);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-around;
  align-items: center;

  .left {
    ul {
      display: flex;
      li {
        list-style: none;
        margin-left: 20px;
        a:-webkit-any-link {
          text-decoration: none;
          color: #adb5bd;
          padding: 8px 12px;
          border-radius: 4px;
          transition: all 0.3s ease;

          &:hover {
            color: #fff;
            background-color: rgba(255, 255, 255, 0.1);
          }

          &.active {
            color: #fff;
            background-color: #4dabf7;
          }
        }
      }
    }
  }

  .right {
    .containerButton {
      display: flex;
      align-items: center;
    }

    line-height: 60px;
    display: flex;
    flex-wrap: nowrap;

    .rightInput {
      display: flex;
      align-items: center;

      :deep(.el-input__inner) {
        height: 36px;
        width: 180px;
        border-radius: 4px 0 0 4px;
      }

      :deep(.el-input-group__append) {
        border-radius: 0 4px 4px 0;
        background-color: #4dabf7;
        border-color: #4dabf7;
        color: white;
        cursor: pointer;
      }
    }

    .btn-dropdown {
      display: flex;
      align-items: center;
    }

    :deep(.el-button) {
      margin: 0 0 0 10px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}
</style>